package com.sbl.bajw.pc.service;

import java.util.HashMap;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.sbl.bajw.common.web.RequestUnit;
import com.sbl.bajw.common.web.SessionUnit;
import com.sbl.bajw.common.web.WebContext;
import com.sbl.bajw.mapper.AppVersionTModelDao;
import com.sbl.bajw.pc.model.AppVersionTModel;
import com.sbl.bajw.util.FileUpload;
import com.sbl.bajw.util.LogUtil;

@Service
public class AppVersionTModelService {

	@Resource
	private AppVersionTModelDao dao;
	
	static Logger log;
	
	static{
		log = LogUtil.getLogger("AppVersionTModel");
	}
	
	public void insert(AppVersionTModel model) throws Exception{
		uploadFile(model);
		model.setCreatedBy(SessionUnit.getUserId());
		dao.insert(model);
	}
	
	public String uploadFile(AppVersionTModel model) throws Exception{
		String id = UUID.randomUUID().toString();
		
		FileItem item = RequestUnit.getFileItem("apk");
		String fileName = "";
		
		String resultPath = "";
		
		if(item != null) {
			String[] fileInfos = item.getName().split("\\.");
			for(int i = 0; i < fileInfos.length - 1; i++){
				fileName += fileInfos[i];
			}
			String path = WebContext.getRequest().getSession().getServletContext().getInitParameter("UploadPath");
			resultPath = "apk/"+FileUpload.saveFile(item, path+"/apk/",fileName);
			log.info(id+"apk上传成功:"+resultPath);
			model.setAppUrl(resultPath);
			model.setAppSize(String.valueOf(item.getSize()));
		}else{
			log.info(id + "没有apk");
		}
		return resultPath;
	}
	
	public HashMap<String, Object> getVersion(String appName){
		HashMap<String, Object> parm = dao.getVersion(appName);
		return parm;
	}
}
